import {formatTime,formatTime2,timeago} from '../../../util/util.js'
const app = getApp()
const db = wx.cloud.database()
const _ = db.command
Page({

  /**
   * 页面的初始数据
   */
  data: {
    title: "",
    txt: "",
    photo: [],
    isLogin: false
  },

  //获取输入信息
  input(event){
    const value = event.detail.value
    this.setData({
      title: value
    })
  },
  textarea(event){
    const value = event.detail.value
    this.setData({
      txt: value,
      isIssue: true
    })
  },

  //上传图片
  login(){
    wx.chooseImage({
      count: 9,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success:(res)=>{
        console.log(res)
        const tempFilePaths = res.tempFilePaths
        this.setData({
          photo:[...this.data.photo,...tempFilePaths],
          isLogin: true
        })
        const photo = []
        for(var i=0; i<this.data.photo.length; i++){
          console.log(this.data.photo[i])
          const cloudPath = "photos/" + app.userInfo._openid +Date.now() + ".png"
          wx.cloud.uploadFile({
            cloudPath,
            filePath: this.data.photo[i],
          }).then((res)=>{
            photo.splice(i,1,res.fileID) 
            this.setData({
              photo
            })
          })

        }
      }
      
    })
  },

  //点击发布按钮
  issue(){
    if(this.data.title || this.data.txt){
      this.myissue()
    }else if(this.data.photo == 0){
      wx.showToast({
        title: '请先发布内容',
      })
    }else{
      this.myissue()
    }

  },

  //信息发布函数
  myissue(){
    wx.showLoading({
      title: '发布中',
    })
    const time = new Date().getTime()
    const content = {time, photo: this.data.photo, title: this.data.title, txt: this.data.txt, autho:app.userInfo._id}
    db.collection('news').doc(app.userInfo._id).update({
      data: {
        content: _.unshift(content),
        time
      }
    }).then((res)=>{
      db.collection('news').doc(app.userInfo._id).field({
        content: true
      }).get().then((res)=>{
        app.userInfo.content = res.data.content
      })
      wx.hideLoading()
      wx.showToast({
        title: '发布成功',
        duration: 2000,  //提示时间
      })
      setTimeout(()=>{
        wx.reLaunch({
          url: '/pages/issue/issue',
        })
      },2000)
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})